//index.js
//获取应用实例


import {
  $wuxDialog
} from '../../dist/index'
import {
  $wuxToptips
} from '../../dist/index'
import { $stopWuxRefresher } from '../../dist/index'

var wxDraw = require("../../utils/wxdraw.min.js").wxDraw;
var Barrage = require("../../utils/barrage.js");
var util = require("../../utils/util.js");
var _post_json = require("../../utils/network.js")._post_json;

const app = getApp()

Page({
  data: {
    pageSize:3,
    second_height: null,
    second_Width: null,
    canvasHeight: 385,
    canvasWidth: null,
    motto: 'Hello World',
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    tagCurrent: 'fastweekly_template',
    tagKey: null,
    wxCanvas: null,
    openId:null,
    //放置返回数据的数组
    isFromSearch: true, // 用于判断searchSongList数组是不是空数组，默认true，空的数组
    searchPageNum: 1, // 设置加载的第几次，默认是第一次
    searchLoading: true, //"上拉加载"的变量，默认false，隐藏
    searchLoadingComplete: true,


    item: {
      searchSongList: [],
      closeBarrageSwitchValue: true,
      closeNoticeSwitchValue: true
    }
    /**开关值 */

  },

  jumpWriteWeeklyPage:function(e){
    var weeklyId = e.currentTarget.dataset.weeklyid;
    wx.navigateTo({
      url: "write/index?weeklyId=" + weeklyId
    })
  },
  tagChange(e) {
    console.log('onChange', e)
    this.setData({
      tagCurrent: e.detail.key,
      tagKey: e.detail.key
    })
  },
  //事件处理函数
  bindViewTap: function () {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  onLoad: function () {
    var that = this
    wx.getStorage({
      key: 'openId',
      success: function (res) {
        that.setData({
          openId: res.data
        })
      }
    });

    wx.setNavigationBarColor({
      frontColor:"#000000",
      backgroundColor: '#FFFF00'
    });
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
    } else if (this.data.canIUse) {
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      })
    }

    
    // 获取系统信息
    wx.getSystemInfo({
      success: function (res) {
        console.log(res);
        // 可使用窗口宽度、高度
        //console.log('height=' + res.windowHeight);
        //console.log('width=' + res.windowWidth);
        // 计算主体部分高度,单位为px
        that.setData({
          second_Width: res.windowWidth,
          second_height: res.windowHeight,
          canvasWidth: res.windowWidth
        })
      }
    })
  },
  getUserInfo: function (e) {
    console.log(e)
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  },
  onReady: function () {
    var canvasHeight = this.data.canvasHeight;
    var canvasWidth = this.data.canvasWidth;
    var context = wx.createCanvasContext('first');
    this.wxCanvas = new wxDraw(context, 0, 0, canvasWidth, canvasHeight);
    var barrage = new Barrage(this.wxCanvas, canvasWidth, canvasHeight);

    var i = 0;
    var hanl = setInterval(function () {
      i++;
      if (i > 1) {
        clearInterval(hanl);
      }
      var randomColor = util.RandomColor();
      barrage.fire(randomColor, "很赞的功能" + i, 18);
    }, util.RandomNumBoth(1000, 2000)) //随机1~2秒发射一次

    this.fetchSearchList();
    /** 
    let that = this;
    _post_json("weekly/getUserWeeklyList", {
      "curr": that.data.searchPageNum,
      "pageSize": this.data.pageSize,
      "openId": this.data.openId
    }).then((res) => {
      that.setData({
        'item.searchSongList': res.data.data.records
      });
    }, () => {
        console.log("请求是失败的");
    });
    */
  },

  //搜索，访问网络
  fetchSearchList: function () {
    let that = this;
    let searchPageNum = that.data.searchPageNum; //把第几次加载次数作为参数
     
    _post_json("weekly/getUserWeeklyList", {
      "curr": searchPageNum,
      "pageSize": 3,
      "openId":this.data.openId
    }).then((data) => {
      console.log(data)
      var queryResult = data.data;
      //判断是否有数据，有则取数据
      if (queryResult.data.records.length != 0) {
        let searchList = [];
        //如果isFromSearch是true从data中取出数据，否则先从原来的数据继续添加
        that.data.isFromSearch ? searchList = queryResult.data.records : searchList = that.data.item.searchSongList.concat(queryResult.data.records)

        that.setData({
          'item.searchSongList': searchList, //获取数据数组
          searchLoading: true //把"上拉加载"的变量设为false，显示
        });
        //没有数据了，把“没有数据”显示，把“上拉加载”隐藏
      } else {
        that.setData({
          searchLoadingComplete: false, //把“没有数据”设为true，显示
          searchLoading: true //把"上拉加载"的变量设为false，隐藏
        });
      }
    }, () => {
      console.log("请求是失败的");
    });
  },
  //滚动到底部触发事件
  searchScrollLower: function () {
    let that = this;
    console.log("searchLoading : " + that.data.searchLoading)
    console.log("searchLoadingComplete : " + !that.data.searchLoadingComplete)

    if (that.data.searchLoading && that.data.searchLoadingComplete) {
      that.setData({
        searchPageNum: that.data.searchPageNum + 1, //每次触发上拉事件，把searchPageNum+1
        isFromSearch: false //触发到上拉事件，把isFromSearch设为为false
      });
      that.fetchSearchList();
    }
  },
  myProfile: function(){
    wx.navigateTo({
      url: "../setting/myprofile/index"
    })
  },
  mangerEntrance: function (event) {
    console.log(event)
    wx.navigateTo({
      url: "../setting/mangerEntrance/index?from=index"
    })

  },
  reward: function(){
    $wuxDialog().confirm({
      resetOnClose: true,
      closable: true,
      title: '赞赏提醒',
      content: '点击确定后长按赞赏图片识别进入赞赏',
      onConfirm(e) {
        wx.previewImage({
          urls: ["https://ioio.kim/wp-content/uploads/2018/10/微信图片_20181007002922-1.jpg"]
        });
      },
      onCancel(e) {
        
      },
    })
    /** 
    wx.navigateTo({
      url: "../setting/reward/index"
    })*/
  },
  barrageSwitch: function (e) {
    this.onSwitchChange('item.closeBarrageSwitchValue', e);
    this.topTipsSucc(e.detail.value ? "开启弹幕~~" : "关闭弹幕~~",2000);
  },
  noticeSwitch: function (e) {
    this.onSwitchChange('item.closeNoticeSwitchValue', e);
    this.topTipsSucc(e.detail.value ? "接收通知~~" : "关闭通知~~", 2000);
  },
  onPulling() {
    console.log('onPulling')
  },
  onRefresh() {
    console.log('onRefresh')
    let that = this;
    
    setTimeout(() => {
      
      that.setData({
        searchPageNum: 1,
        isFromSearch: true,
        searchLoading: true, 
        searchLoadingComplete: true
      })

      this.fetchSearchList();

      

      $stopWuxRefresher()
    }, 2000)
  },
  topTipsSucc(msg, duration){
    $wuxToptips().success({
      hidden: false,
      text: msg,
      duration: duration,
      success() { },
    })
  },
  //全部的开关切换都需要调用这个方法切换
  onSwitchChange(field, e) {
    this.setData({
      [field]: e.detail.value
    })
  }
})